import { Action } from "redux";
import { ListType } from "../../views/home";

export interface CarState extends ListType {
  count: number;
  state: boolean;
}

const initState = {
  carList: [] as CarState[],
};

const carReducer = (state = initState, action: any) => {

  const { type, payload } = action;
  switch (type) {
    case "addCarList": {
      // 1. 购物车是否存在存在
      const item = state.carList.find((v) => v.id === payload.id);
      if (item) {
        item.count++;
      } else {
        state.carList.push(payload);
      }
      console.log(state.carList)
      return {
        ...state,
        carList: [...state.carList],
      };
    }
    case "subCarList": {
      // 1. 购物车是否存在存在
      const item = state.carList.find((v) => v.id === payload.id);
      if (item) {
        item.count--;
      }
      console.log(state.carList)
      return {
        ...state,
        carList: [...state.carList],
      };
    }
    case "delCarList": {
      return {
        ...state,
        carList: state.carList.filter((v) => v.id !== payload.id),
      };
    }
    case "clearCarList": {
      return {
        ...state,
        carList: [],
      };
    }
    case "delCarListByState": {
      return {
        ...state,
        carList: state.carList.filter(v => !v.state),
      };
    }
    case "changeTotalState": {
      state.carList.forEach((v) => (v.state = payload));
      return {
        ...state,
        carList: [...state.carList],
      };
    }
    case "changeOneState": {
      // 1. 购物车是否存在存在
      const item = state.carList.find((v) => v.id === payload.id);
      if (item) item.state = !item.state;
      return {
        ...state,
        carList: [...state.carList]
      };
    }
    default: return state
  }
};

export default carReducer;
